package jch.learn.java.advanced.chapter2_InputAndOutput.randomAccess;

import java.io.*;
import java.time.LocalDate;

// 随机访问文件
public class RandomAccessTest {

    public static void main(String[] args) throws IOException {
        Employee[] staff = new Employee[3];
        staff[0] = new Employee("张三", 12240, 2001, 1, 1);
        staff[1] = new Employee("刘基", 90001, 1990, 9, 10);
        staff[2] = new Employee("伍佰", 199900, 1999, 10, 10);
        String path = RandomAccessTest.class.getResource("/chapter2/employee.dat").getPath();
        try (DataOutputStream out = new DataOutputStream(new FileOutputStream(path))) {
            for (Employee e : staff) {
                writeData(out, e);
            }
        }
        // 随机访问文件 读取
        try (RandomAccessFile in = new RandomAccessFile(path, "r")) {
            int n = (int) (in.length() / Employee.RECORD_SIZE);
            Employee[] newStaff = new Employee[n];
            for (int i = n - 1; i >= 0; i--) {
                newStaff[i] = new Employee();
                in.seek((long) i * Employee.RECORD_SIZE);
                newStaff[i] = readData(in);
            }
            for (Employee e : newStaff) {
                System.out.println(e);
            }
        }
    }

    /**
     * 读取员工信息
     *
     * @param in 随机访问文件流
     * @return 员工信息
     */
    private static Employee readData(RandomAccessFile in) throws IOException {
        String name = DataIO.readFixedString(Employee.NAME_SIZE, in);
        double salary = in.readDouble();
        int year = in.readInt();
        int month = in.readInt();
        int day = in.readInt();
        return new Employee(name, salary, year, month, day);
    }

    /**
     * 写出员工信息
     *
     * @param out 字节输出流
     * @param e   员工信息
     * @throws IOException 写出流IO异常
     */
    private static void writeData(DataOutputStream out, Employee e) throws IOException {
        DataIO.writeFixedString(e.getName(), Employee.NAME_SIZE, out);
        out.writeDouble(e.getSalary());
        LocalDate hireDay = e.getHireDay();
        out.writeInt(hireDay.getYear());
        out.writeInt(hireDay.getMonthValue());
        out.writeInt(hireDay.getDayOfMonth());
    }

}
